package com.xiaoq.social.repository.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.social.entity.FansTagMasterEntity;
import com.xiaoq.social.repository.IFansTagMasterRepository;

@Repository
public class FansTagMasterRepositoryImpl implements IFansTagMasterRepository {
	
	@Autowired
	private Datastore datastore;
	
	@Autowired
	private IdGenerator idGenerator;
	
	private static final Logger LOG = LoggerFactory.getLogger(FansTagMasterRepositoryImpl.class);

	@Override
	public boolean executeFansTagMaster(String shopId, List<String> tags) {
		Query<FansTagMasterEntity> fansMasterQuery = datastore.find(FansTagMasterEntity.class);
		UpdateOperations<FansTagMasterEntity> fansMasterOperations = datastore.createUpdateOperations(FansTagMasterEntity.class);
		if(StringUtils.isNotEmpty(shopId)){
			fansMasterQuery.field("shopId").equal(shopId);
			if(fansMasterQuery.count()!=0){
				fansMasterOperations.set("tags", tags);
				LOG.info("对已有店铺标签进行修改！");
				datastore.update(fansMasterQuery, fansMasterOperations);
				return true;
			}else{
				FansTagMasterEntity fansTagMaster = new FansTagMasterEntity();
				String id = idGenerator.nextId();
				LOG.info("对新建店铺的标签进行添加Id是："+id);
				fansTagMaster.setId(id);
				fansTagMaster.setShopId(shopId);
				fansTagMaster.setTags(tags);
				datastore.save(fansTagMaster);
				return true;
				
			}
			
			
		}else{
			LOG.error("请指明详细的shopId!");
		}
		return false;
	}

	@Override
	public List<FansTagMasterEntity> findFansTagMasterList(String shopId) {
		
		Query<FansTagMasterEntity> fansTagQuery = datastore.find(FansTagMasterEntity.class);
		List<FansTagMasterEntity> fansTagMasterList = new ArrayList<>();
		if(StringUtils.isNotEmpty(shopId)){
			fansTagQuery.field("shopId").equal(shopId);
			fansTagMasterList = fansTagQuery.asList();
		}
		return fansTagMasterList;
	}

}
